Skip to content

手写 instanceof

js
function Animation(name) {
  this.name = name;
}
const cat = new Animation("cat");

// console.log(cat instanceof Animation);

const myInstanceof = (left, target) => {
  if (!left || !target) return false;
  const right = target.prototype;
  while (true) {
    if (left === right) return true;
    if (!left) return false;
    left = left.__proto__;
  }
};

const myInstanceofType2 = (left, target) => {
  if (!left || !target) return false;
  let leftValue = left.__proto__;
  let rightValue = target.prototype;
  while (true) {
    if (leftValue === rightValue) return true;
    if (!leftValue) return false;
    leftValue = leftValue.__proto__;
  }
};
console.log(myInstanceof(cat, Animation));
console.log(myInstanceof(cat, Object));
console.log(myInstanceofType2(cat, Animation));
console.log(myInstanceofType2(cat, Object));

当 instaceof 前面是 str 原始数据类型的时候,回执行 [Symbol.hasInstance] 方法

js
var str = "test";
// string[Symbol.hasInstance](str) ===> false

class CustomStr {
  [Symbol.hasInstance](x) {
    return typeof x === "string";
  }
}
console.log("hello" instanceof CustomStr); // === true

typeof、数据类型、instanceof、

typeof为什么对null错误的显示

这只是 JS 存在的一个悠久 Bug。在 JS 的最初版本中使用的是 32 位系统,为了性能考虑使用低位存储变量的类型信息,000 开头代表是对象然而 null 表示为全零,所以将它错误的判断为 object

typeof('abc')和 typeof 'abc'都是 string, 那么 typeof 是操作符还是函数

typeof 的返回值之一为'function',如果 typeof 为 function,那么 typeof(typeof) 会返回'function',但是经测试,上述代码浏览器会抛出错误。因此可以证明 typeof 并非函数。

既然 typeof 不是函数,那 typeof 后面的括号的作用是?

括号的作用是进行分组而非函数的调用。—— 《javascript 高级程序设计》

js
typeof (((func))); // is equal to typeof func

typeof function 会显示什么

function

数据类型

  • 基础数据类型 7

    • Boolean Number String undefined null Bigint Symbol
    • Symbol : ES6 引入的一种新的原始值,表示独一无二的值,主要为了解决属性名冲突问题。 Bigint :ES2020 新增加,是比 Number 类型的整数范围更大。
  • 引用数据类型:1种

    • Object对象(包括普通Object、Function、Array、Date、RegExp、Math)

在 MIT 许可下发布